from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse, HttpResponseForbidden, HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.http import require_POST, require_http_methods

from .forms import StudentForm, StudentModelForm
from .models import essay, Tag, classification, Comment, CommentLike, Student, user_info
from django.views import View
import markdown


# Create your views here.
def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            login(request, user)
            return redirect('/article/')
        else:
            return render(request, '登录.html', {'error_message': '用户不存在或密码错误'})
    return render(request, '登录.html')


def user_logout(request):
    logout(request)
    return redirect('/article/')


class RegisterView(View):
    def get(self, request):
        return render(request, '注册.html')

    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        password_again = request.POST['password-again']
        try:
            if not username:
                return render(request, '注册.html', {'error_message': '用户名不能为空'})
            else:
                users = authenticate(request, username=username, password=password)
            if users:
                return render(request, '注册.html', {'error_message': '用户名已存在'})
            elif not password and not password_again:
                return render(request, '注册.html', {'error_message': '密码不能为空'})
            elif password != password_again:
                return render(request, '注册.html', {'error_message': '两次密码输入不一致'})
            else:
                user_info.objects.create(username=username)
                User.objects.create_superuser(username=username, password=password)

        except:
            return render(request, '注册.html', {'error_message': '用户已存在'})

        return redirect('login')


def to_register(request):
    return redirect('register')

#
# classification_list = list(classification.objects.values_list('name', flat=True).distinct())
# tag_list = list(Tag.objects.values_list('name', flat=True).distinct())


def article_list(request, tag_type=None):
    articles = essay.objects.all().order_by('-create_time')
    page = None
    if tag_type:
        tag_type = tag_type.split('_')
        for i in tag_type:
            if i in classification_list:
                categories = classification.objects.filter(name=i).first()
                articles = articles.filter(classifier=categories)
            elif i in tag_list:
                tags = Tag.objects.filter(name=i).first()
                articles = articles.filter(tag=tags)
            elif 'page' in i:
                page = int(i[5:])
            else:
                year = i.split('-')[0]
                month = i.split('-')[-1]
                articles = articles.filter(create_time__year=year, create_time__month=month)
    articles = articles.order_by('-create_time')
    tags = Tag.objects.all()
    classes = classification.objects.all()
    classes_with_counts = {item: item.essay_set.count() for item in classes}
    paginator = Paginator(articles, 3)
    page_obj = paginator.get_page(page)

    if request.user.is_authenticated:
        user_info_instance = user_info.objects.get(user=request.user)
        return render(request, '首页.html', {'username': 'request.user.username', 'articles': page_obj, 'tags': tags,
                                             'classes': classes, 'tag_type': tag_type,
                                             'classes_with_counts': classes_with_counts,
                                             'user_info': user_info_instance})
    else:
        return render(request, '首页.html', {'articles': page_obj, 'tags': tags, 'classes': classes,
                                             'tag_type': tag_type, 'classes_with_counts': classes_with_counts})


def detail(request, page_id):
    article = get_object_or_404(essay, id=page_id)
    comments = Comment.objects.filter(article_id=page_id, parent__isnull=True).order_by('-create_time')
    return render(request, '../templates/详情页.html', {'article': article, 'comments': comments})


def to_article(request):
    return redirect('article/')


@login_required
def user_center(request):
    user_info_instance = user_info.objects.get(user=request.user)
    article = essay.objects.filter(author=request.user)
    return render(request, '个人.html', {'user_info': user_info_instance, 'user_articles': article})


def delete_essay(request, essay_id):
    essay_instance = essay.objects.get(id=essay_id)
    if request.user == essay_instance.author:  # 确保用户有权限删除文章
        essay_instance.delete()
        return redirect('user')


def edit_essay(request, essay_id):
    if request.method == 'POST':
        essay_instance = essay.objects.get(id=essay_id)
        if request.user == essay_instance.author:  # 确保用户有权限编辑文章
            title = request.POST['title']
            content = request.POST['content']
            classifier = request.POST['category']

            tags_input = request.POST['tags']
            tags_list = [tag.strip() for tag in tags_input.split(',')]
            essay_instance.tag.clear()
            for tag_name in tags_list:
                if tag_name:
                    tag_instance, created = Tag.objects.get_or_create(name=tag_name)
                    essay_instance.tag.add(tag_instance)

            essay_instance.title = title
            essay_instance.content = content
            essay_instance.classifier = classification.objects.get(name=classifier)
            essay_instance.save()
            return redirect('user')
        else:
            return render(request, '修改.html', {'error_message': '你没有权限修改这篇文章'})
    else:
        essay_instance = essay.objects.get(id=essay_id)
        return render(request, '修改.html', {'article': essay_instance})


def submit_essay(request):
    if request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']
        classifier = request.POST['category']

        tags_input = request.POST['tags']
        tags_list = [tag.strip() for tag in tags_input.split(',')]

        author = request.user

        classification.objects.create(name=classifier)
        essay_instance = essay(title=title, content=content, classifier=classification.objects.get(name=classifier),
                               author=author)
        essay_instance.save()

        for tag_name in tags_list:
            if tag_name:
                tag_instance, created = Tag.objects.get_or_create(name=tag_name)
                essay_instance.tag.add(tag_instance)

        return redirect('user')
    else:
        return render(request, '发布.html')


def change_message(request):
    if request.method == 'POST':

        user_info_instance = user_info.objects.get(user=request.user)
        head = request.FILES.get('avatar')
        username = request.POST['username']
        age = request.POST['age']
        phone = request.POST['phone']
        desc = request.POST['desc']

        user_instance = get_object_or_404(User, username=request.user)
        user_info_instance.user = user_instance
        current_user = User.objects.get(username=request.user.username)
        current_user.username = username
        current_user.save()

        user_info_instance.age = age
        user_info_instance.head_img = head
        user_info_instance.phone = phone
        user_info_instance.desc = desc
        user_info_instance.save()
        return redirect('user')
    else:
        user_info_instance = user_info.objects.get(user=request.user)
        return render(request, '个人信息.html', {'userinfo': user_info_instance})


def submit_comment(request, page_id):
    if request.method == 'POST':
        comment_text = request.POST.get('comment')

        # 读取当前文章的评论
        comments = request.session.get('comments', {})
        if page_id not in comments:
            comments[page_id] = []

        # 添加新的评论
        comments[page_id].append(comment_text)

        # 保存到会话
        request.session['comments'] = comments

        Comment.objects.create(text=comment_text, user=request.user, article_id=page_id)

        return redirect('detail', page_id=page_id)


@login_required
@require_http_methods(["DELETE"])
def delete_comment(request, comment_id):
    comment = Comment.objects.get(id=comment_id)
    if request.user == comment.user:  # 确保用户有权限删除评论
        comment.delete()
        return JsonResponse({'success': True})
    return HttpResponseForbidden("你没有权限删除这条评论")


@login_required
@require_POST
def like_comment(request, comment_id):
    comment = get_object_or_404(Comment, id=comment_id)

    # 检查用户是否已经点赞
    liked = CommentLike.objects.filter(user=request.user, comment=comment).first()

    if liked:
        # 如果用户已经点赞，取消点赞
        liked.delete()
        comment.like_count -= 1  # 更新点赞计数
        comment.save()
        return JsonResponse({'success': True, 'like_count': comment.like_count, 'message': '已取消点赞'})

    # 用户未点赞，创建新的点赞记录
    CommentLike.objects.create(user=request.user, comment=comment)

    # 更新评论的点赞计数
    comment.like_count += 1
    comment.save()

    return JsonResponse({'success': True, 'like_count': comment.like_count, 'message': '已点赞'})


def search(request):
    keyword = request.GET.get('query')
    articles = essay.objects.filter(
        Q(title__icontains=keyword) |  # 匹配标题
        Q(classifier__name__icontains=keyword) |  # 匹配分类器的名称
        Q(author__username__icontains=keyword)  # 匹配作者的名称
    ).order_by('-create_time')
    return render(request, '搜索.html', {'articles': articles})


# 以下与本项目无关
def form1(request):
    if request.method == 'GET':
        print(request.method)
        return render(request, 'test/form1.html')
    else:
        name = request.POST.get('name', '')
        age = request.POST.get('age', 0)
        print(name, age)
        student = Student(name=name, age=age)
        student.save()
        return HttpResponse('添加成功')


def form2(request):
    if request.method == 'GET':
        form = StudentForm()
    else:
        form = StudentForm(request.POST)
        if form.is_valid():
            name = form.data.get('name', '')
            age = form.data.get('age', 0)
            student = Student(name=name, age=age)
            student.save()
            return HttpResponse('添加成功')

    return render(request, 'test/form2.html', {'form': form})


def form3(request):
    print(request.method)
    if request.method == 'GET':
        form = StudentModelForm()
    else:
        form = StudentModelForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('添加数据成功')

    return render(request, 'test/form3.html', {'form': form})
